package com.example.mvc.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class LoginFilter  implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //为了获取到session转为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //判断访问资源路径是否和登录注册相关
        //1,在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/login.jsp","/imgs/","/css/","/loginServlet","/register.jsp","/registerServlet","/checkCodeServlet"};
        //2,获取当前访问的资源路径
        String url = request.getRequestURL().toString();

        //3,遍历数组，获取到每一个需要放行的资源路径
        for (String u : urls) {
            //4,判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
            /*
                比如当前访问的资源路径是  /mvc_prorject_war/login.jsp
                而字符串 /mvc_prorject_war/login.jsp 包含了  字符串 /login.jsp ，所以这个字符串就需要放行
            */
                    if(url.contains(u)){
                //找到了，放行
                filterChain.doFilter(request, servletResponse);
                //break;
                return;
            }
        }


        //获取到session对象
        HttpSession session = request.getSession();
        //从session获取到user属性的值
        Object user = session.getAttribute("user");
        if (user!=null){ //不为空，即为已经登录了，可以放行
            //放行
            filterChain.doFilter(request,servletResponse);
        }else {
            //未登录，跳转到登录界面，并提醒用户未的登录
            request.setAttribute("login_msg","尚未登录");
            request.getRequestDispatcher("/login.jsp").forward(request,servletResponse);
        }


    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void destroy() {


    }
}
